import React, { useMemo, useRef, useState } from "react";
import { FloatLayout as FloatLayoutCustom } from "../components/index";

import { OverlayProps, TopViewOptions } from "../../types/uses/useTopView";

export const TopContext = React.createContext({} as OverlayProps);

const TopProvider: React.FC = props => {

  const [opened, setOpened] = useState(false)
  const [customeView, setCustomeView] = useState<React.FC>()
  const optionsRef = useRef<TopViewOptions>()
  const onCloseRef = useRef<(data: boolean) => void>()

  const currentComponentId = useRef<number>() // 当前显示的组件id


  const popup = (compObj: { id: number, component: React.FC }, options: TopViewOptions = {}): Promise<boolean | undefined> => {
    optionsRef.current = { ...options, closeable: (options.closeable === undefined ? true : options.closeable) }
    currentComponentId.current = compObj.id

    setCustomeView(compObj.component)
    setOpened(true)
    return new Promise((resolve) => {
      onCloseRef.current = resolve
    });
  }

  const topView = useMemo(() => {
    return <FloatLayoutCustom
      isOpened={opened}
      onClose={() => {
        if (optionsRef.current && optionsRef.current.closeable) {
          // 清除当前组件id
          currentComponentId.current = 0
          setOpened(false)
          optionsRef.current && optionsRef.current.hasInput && setCustomeView(null as any)
          onCloseRef.current?.(true)
        }
       
      }}
      isCover={optionsRef.current?.isCover}
      style={optionsRef.current && optionsRef.current.type === 'slid-up' ? "sheet" : 'alert'}
      floatStyle={optionsRef.current?.floatStyle}
      maskStyle={optionsRef.current?.maskStyle}
      floatClassName={optionsRef.current?.floatClassName}
      containerStyle={optionsRef.current?.containerStyle}
    >
      {customeView}
    </FloatLayoutCustom>
  }, [opened, customeView])

  const close = (componentId: number) => {
    // 与当前显示的为同一组件
    if (currentComponentId.current == componentId) {
      // 清除当前组件id
      currentComponentId.current = 0
      forcedClose()
    }
  }

  const forcedClose = () => {
    optionsRef.current && optionsRef.current.hasInput && setCustomeView(null as any)
    setOpened(false)
  }

  return (
    <TopContext.Provider value={{ popup, close, forcedClose, topView }}>
      {props.children}
    </TopContext.Provider>
  );
};
export default TopProvider